// Initialize your app
var myApp = new Framework7({
    pushState: true
    //,statusbarOverlay: true
});

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    dynamicNavbar: true
});

document.documentElement.style.webkitTouchCallout = "none";
document.documentElement.style.webkitUserSelect = "none";

Hybrid.ready(function(){
    var hybrid = this;
    var light = false;

    setTimeout(function(){
        //hybrid.callAction('SplashScreen/hideSplashScreen', {})
        hybrid.callAction('Core/playVibrate');
        hybrid.callAction('Core/setIconBadge', {badge: 0});
    }, 3000);

    //hybrid.showToast({
    //    message: "初始化完成"
    //});

    var backgroundColor = '#58c4e6';
    var color = '#FFFFFF';

    $$('.statusbar-overlay').css({
        backgroundColor: backgroundColor
    });
    $$('.navbar,.subnavbar').css({
        backgroundColor: backgroundColor,
        color: color
    });
    $$('.navbar a.link,.subnavbar a.link').css({
        color: color
    });

    //设置 Native 主题色
    hybrid.setTheme(color, backgroundColor, true, function () {
        //hybrid.makeToast("设置 Native 主题色完成", 3.0);
        /*hybrid.showIndicator();
        setTimeout(function(){
            hybrid.hideIndicator();
            hybrid.getNetworkStatus(function(){
                myApp.alert(JSON.stringify(arguments))
            });
        }, 2000)*/
    });

    $$(document).on("click", 'a[target="_blank"]', function(e){
        var $this = $$(this);
        hybrid.openWindow($this.data('href') || this.href);
    });

    $$(document).on('click','.open-mqq',function(){
        hybrid.openURL(this.href, function(status, data){
            if(!status){
                hybrid.makeToast('唤醒失败!应用可能未安装.');
            }
        });
    });

    $$(document).on('click', '#share', function(){
        var social = hybrid.plugin.Social;
        /*social.showShareActionSheet({
            title: 'hello',
            text: 'wwwww',
            contentType: social.contentType.Text,
            platforms: [
                social.platformType.Renren,
                social.platformType.QQ,
                social.platformType.Mail,
                social.platformType.SinaWeibo,
                social.platformType.SMS
            ]
        }, function(status, data){
            //logger.log(status);
            alert(JSON.stringify(arguments))
        });*/

        /*social.share({
            title: 'hello',
            text: 'wwwww',
            contentType: social.contentType.Text,
            platform: social.platformType.QQ
        }, function(status, data){
            //logger.log(status);
            alert(JSON.stringify(arguments))
        });*/

        /*social.authorize(social.platformType.SinaWeibo,function(status, data){
            alert(JSON.stringify(arguments));
            if(status){
                social.getFriends({
                    platform: social.platformType.SinaWeibo,
                    page: 1,
                    pageSize: 10
                }, function(){
                    alert(JSON.stringify(arguments))
                })
            }
        });*/

        /*hybrid.plugin.share({
            title: 'hello',
            text: 'wwwww',
            items: [

            ]
        }, function(status, data){
            //logger.log(status);
            alert(JSON.stringify(arguments))
        });*/
        //hybrid.logger.log('asdf');

        /*hybrid.setNavigationBarHide(false);
        hybrid.setTheme('#ffffff', '#ff6600', light = !light, function(){
            hybrid.setNavigationBarHide(!light);
            hybrid.plugin.QRCode.scan(function(){
                myApp.alert(JSON.stringify(arguments))
            });
        });*/

        /*hybrid.callHandler('Action', {
            action: 'CoreAction',
            method: 'hello',
            params: 'ok'
        }, function(){

        })*/

        /*hybrid.plugin.QRCode.generator({
            text: 'adfasdf你好啊发打发打发了房价ADSL发了多少分',
            size: 300,
            margin: 0
        }, function(status, data){
            myApp.alert('<img height="250" src="data:image/png;base64,' + data + '"/>', '分享二维码');
        });*/

        /*hybrid.callAction('ImagePicker/selectImages',{
            editing: true,
            sourceType: 1,
            upload: true,
            uploadFormAction: '',
            uploadFormName: ''
        }, function(status, info){
            alert(JSON.stringify(arguments))
        })*/

        /*var imagePicker = hybrid.plugin.imagePicker;
        imagePicker.open({
            editing: true,
            upload: true,
            uploadFormAction: 'http://m.blog.csdn.net/blog/dragonluckydog2479/11974501',
            uploadFormName: 'img',
            sourceType: imagePicker.SourceType.Other
        }, function(status, data){
            //alert(JSON.stringify(arguments))
            if(status){
                myApp.alert('<img width="230" src="' + data.url + '"/>');
            }else{
                myApp.alert(data)
            }
        });*/

    });

    /*hybrid.callHandler('hideSplash',{},function(){

    });*/
    hybrid.addEventListener('GeTuiSdkDidReceivePayload',function(e){
        myApp.alert(JSON.stringify(e.data))
    })

    //alert(JSON.stringify(hybrid.device));
    var colors = ['58c4e6', '808080', '000000', 'ADD8E6', 'FFA500', 'FFC0CB', '008000', 'FF0000', 'FF6600'];
    var colorIndex = 0;
    function autoChangeTheme(){
        setTimeout(autoChangeTheme, 1000);
        var backgroundColor = '#' + colors[colorIndex++ % colors.length];
        $$('.statusbar-overlay').css({
            backgroundColor: backgroundColor
        });
        $$('.navbar,.subnavbar').css({
            backgroundColor: backgroundColor
        });

        //设置 Native 主题色
        hybrid.setTheme(color, backgroundColor, true, function () {
            //hybrid.makeToast("设置 Native 主题色完成", 3.0);
        });
    }
    $$('.change-theme').click(autoChangeTheme);

    $$(document).on('change', 'input[name="color-radio"]',function () {
        var colorTxt = $$(this).val();
        var backgroundColor = '#58c4e6';
        var color = '#FFFFFF';
        var lightStatusBar = true;
        switch (colorTxt){
            case 'blue':
                backgroundColor = '#58c4e6';
                break;
            case 'gray':
                backgroundColor = '#808080';
                break;
            case 'black':
                backgroundColor = '#000000';
                break;
            case 'lightblue':
                backgroundColor = '#ADD8E6';
                break;
            case 'yellow':
                backgroundColor = '#FFFF00';
                color = '#000000';
                lightStatusBar = false;
                break;
            case 'orange':
                backgroundColor = '#FFA500';
                break;
            case 'pink':
                backgroundColor = '#FFC0CB';
                break;
            case 'green':
                backgroundColor = '#008000';
                break;
            case 'red':
                backgroundColor = '#FF0000';
                break;
            case 'orangered':
                backgroundColor = '#FF6600';
                break;
        }
        $$('.statusbar-overlay').css({
            backgroundColor: backgroundColor
        });
        $$('.navbar,.subnavbar').css({
            backgroundColor: backgroundColor,
            color: color
        });
        $$('.navbar a.link,.subnavbar a.link').css({
            color: color
        });

        Hybrid.ready(function(){
            var hybrid = this;
            //设置 Native 主题色
            hybrid.setTheme(color, backgroundColor, lightStatusBar, function () {
                hybrid.makeToast("设置 Native 主题色完成", 3.0);
            });
        })
    });


});

$$(document).on('pageInit', '.page[data-page="social"]', function(){

    Hybrid.ready(function(){
        var hybrid = this;
        var social = hybrid.plugin.Social;

        $$('a.select-share').click(function(){

            social.showShareActionSheet({
                title: '分享测试',
                text: '这是一个分享测试.',
                contentType: social.contentType.Text,
                platforms: [
                    social.platformType.Renren,
                    social.platformType.QQ,
                    social.platformType.Mail,
                    social.platformType.SinaWeibo,
                    social.platformType.SMS
                ]
            }, function (status, data) {
                if(status){
                    myApp.alert('分享成功.');
                }else{
                    myApp.alert(JSON.stringify(data))
                }
            });
        });

        $$('a.weibo-share').click(function(){
            social.share({
                title: '分享测试',
                text: '这是一个分享测试.',
                contentType: social.contentType.Text,
                platform: social.platformType.SinaWeibo
            }, function (status, data) {
                if(status){
                    myApp.alert('分享成功.');
                }else{
                    myApp.alert(JSON.stringify(data))
                }
            });
        });

        $$('a.weibo-authorize').click(function(){

            social.authorize(social.platformType.SinaWeibo, function (status, data) {
                if (status) {
                    myApp.alert(
                        'uid: ' + data['uid'] + '<br>' +
                        'nickname: ' + data['nickname'],
                        '授权成功');

                }else{
                    myApp.alert('授权失败');
                }
            });
        });

    });
});

$$(document).on('pageInit', '.page[data-page="socialFriends"]', function(){

    Hybrid.ready(function() {

        var hybrid = this;
        var social = hybrid.plugin.Social;
        myApp.showIndicator();
        social.getFriends({
            platform: social.platformType.SinaWeibo,
            page: 1,
            pageSize: 10
        }, function (status, data) {
            myApp.hideIndicator();
            if(status){
                if(data && data.users){
                    var lis = [];
                    hybrid.utils.forEach(data.users, function(i, user){
                        lis.push('<li>\n    <a href="#" class="item-link item-content">\n        <div class="item-media"><img src="' + user.icon + '" width="44"></div>\n        <div class="item-inner">\n            <div class="item-title-row">\n                <div class="item-title">' + user.nickname + '</div>\n            </div>\n            <div class="item-text">' + (user.aboutMe||'...') + '</div>\n        </div>\n    </a>\n</li>');
                    });
                    $$('#friends_list_view').html(lis.join('\n'));
                }
            }else{
                myApp.alert(JSON.stringify(data))
            }
        })
    });
});



$$(document).on('pageInit', '.page[data-page="qrcode"]', function(){

    Hybrid.ready(function() {

        var hybrid = this;
        var qrcode = hybrid.plugin.QRCode;

        $$('a.scan-qrcode').click(function(){
            qrcode.scan({
                title: "扫描二维码"
            }, function(status, data){
                if(status){
                    myApp.alert(JSON.stringify(data));
                }else{
                    myApp.alert('扫码失败');
                }
            });
        });

        $$('a.generator-qrcode').click(function(){
            qrcode.generator({
                text: "抱歉,此功能暂时不可用!\nhello ...",
                size: 240,
                margin: 1
            }, function(status, data){
                if(status){
                    myApp.alert('<img src="data:image/png;base64,' + data + '" height="240" width="240"/>');
                }else{
                    myApp.alert('生成失败');
                }
            });
        });
    });
});


$$(document).on('pageInit', '.page[data-page="pay"]', function(){

    Hybrid.ready(function() {

        var hybrid = this;
        var alipay = hybrid.plugin.AliPay;

        $$('a.alipay-payorder').click(function(){

            alipay.payOrder({
                order: {"partner":"2088911200828478","sellerId":"2088911200828478","outTradeNo":"00141583635838172286077046","subject":"账户充值","body":"账户充值","totalFee":"1.00","notifyUrl":"http://statics.maosui.com/Res/AlipayNotify.ashx","service":"mobile.securitypay.pay","paymentType":"1","inputCharset":"utf-8","itBPay":"10m","showUrl":"http://statics.maosui.com/Res/AlipayNotify.ashx","sign":"bq1040N7TXYEQYblVf6hZ3dVbzN9O/1jpssRXboC1R26mjdlOhUN22nnlvVGPZOrCnRP2ZpLqnizGTNZr5Kxv6AGppP2K1TBHM8FeBqD8Ry3+XPfZGQ593zt4mM3ROTdDAK8MsWqmzkoKXl6yiQ6yFjeTop/J1k83d+quwJXTuA=","signType":"RSA"},
                schemeStr: 'maosuizj'
            }, function(status, data){
                alert(JSON.stringify(arguments));
            });
        });
    });
});


$$(document).on('pageInit', '.page[data-page="imagePicker"]', function(){

    Hybrid.ready(function() {

        var hybrid = this;
        var imagePicker = hybrid.plugin.imagePicker;

        $$('a.select-image-picker').click(function(){

            imagePicker.open({

            }, function(status, data){
                if(status){
                    $$('#imagePickerPreview').html('<img src="' + data.url + '" width="100%"/>');
                }else{
                    alert("错误:\n" + JSON.stringify(data));
                }
            });
        });

        $$('a.editor-image-picker').click(function(){
            imagePicker.open({
                editing: true // 是否启用图片编辑
            }, function(status, data){
                if(status){
                    $$('#imagePickerPreview').html('<img src="' + data.url + '" width="100%"/>');
                }else{
                    alert("错误:\n" + JSON.stringify(data));
                }
            });
        });

        $$('a.upload-image-picker').click(function(){

            imagePicker.open({
                editing: true, // 是否启用图片编辑
                upload: true, // 是否上传到服务器
                uploadFormAction: 'http://m.blog.csdn.net/blog/dragonluckydog2479/11974501',
                uploadFormName: 'img'
            }, function(status, data){
                if(status){
                    $$('#imagePickerPreview').html('<img src="' + data.url + '" width="100%"/>');
                }else{
                    myApp.alert("错误:\n" + JSON.stringify(data));
                }
            });
        });

    });

});


/***
 * 位置管理页
 */
$$(document).on('pageInit', '.page[data-page="locationManager"]', function(){

    Hybrid.ready(function(){

        var hybrid = this;

        $$('a.get-current-location').click(function(){
            hybrid.geolocation.getCurrentLocation(function(status, data){
                hybrid.makeToast(JSON.stringify(data));
            });
        });

        var wId;
        $$('a.start-m-location').click(function(){
            var $this = $$(this);
            if($this.data('watchPosition')){
                hybrid.geolocation.stopWatch(wId, function(){
                    $this.data('watchPosition', false);
                    $this.html('监听位置');
                    $$('<div>已停止监听</div>').appendTo('#m-location-result');
                });
            }else{
                wId = hybrid.geolocation.watchPosition({}, function(p){
                    $$('<div>' + JSON.stringify(p) + '</div>').appendTo('#m-location-result');
                });
                $this.data('watchPosition', true);
                $this.html('停止监听');
                $$('<div>开始监听...</div>').appendTo('#m-location-result');
            }
        });

    });
});

/***
 * 位置管理页
 */
$$(document).on('pageInit', '.page[data-page="audio"]', function(){

    Hybrid.ready(function(){

        var hybrid = this;
        var audioUrl ;

        function voChange(e){
            var progress = e.data.progress || 0;
            $$('#re_vo_height').css('height', (progress) + '%');
            $$('#audio_re_vo').html(JSON.stringify(e.data.progress));
        }

        $$('a.start-record').click(function(){
            hybrid.callAction('MAudio/startRecord',{},function(status, data){
                hybrid.showToast('已开始录音.');
                $$('#re_vo_div').show();
                hybrid.addEventListener("audioRecorderPowerChange", voChange);
            });
        });


        $$('a.stop-record').click(function(){
            hybrid.callAction('MAudio/stopRecord',{},function(result){
                //myApp.alert(JSON.stringify(arguments));
                $$('#re_vo_div').hide();
                var status = result.status;
                var data = result.data;
                if(status){
                    audioUrl = data.file;
                }else{
                    myApp.alert(JSON.stringify(arguments));
                }
            });
            hybrid.removeEventListener("audioRecorderPowerChange", voChange);
        });

        $$('a.play-record').click(function(){
            hybrid.callAction('MAudio/playAudio',{
                url: audioUrl
            },function(){
                myApp.alert(JSON.stringify(arguments));
            });
        });


        $$('#record_button').on('touchstart', function(e){
            $$('#re_vo_div').show();
            hybrid.callAction('MAudio/startRecord',{},function(status, data){
                hybrid.addEventListener("audioRecorderPowerChange", voChange);
            });
        }).on('touchend', function(e){
            $$('#re_vo_div').hide();
            hybrid.callAction('MAudio/stopRecord',{},function(result){
                var status = result.status;
                var data = result.data;
                if(status){
                    audioUrl = data.file;
                }else{
                    myApp.alert(JSON.stringify(arguments));
                }
            });
            hybrid.removeEventListener("audioRecorderPowerChange", voChange);
        });
    });
});

$$(document).on('pageInit', '.page[data-page="video"]', function(){

    Hybrid.ready(function(){
        var hybrid = this;
        var videoURL = '/Common/20151221/4f1d3b37d55d48f7b04d55a8eac70acc.mp4';

        $$('.start-video-record').click(function(){
            hybrid.plugin.video.record({
                minTime: 2,
                maxTime: 30
            },function(status, data){
                if(status){
                    hybrid.file.upload({
                        file: data.file
                    }, function(sts, body){
                        if(sts){
                            myApp.alert(JSON.stringify(body), "上传成功");
                            videoURL = body.fileUrl || '';
                        }else{
                            myApp.alert(body);
                        }
                    });
                }else{

                }
            })
        });

        $$('.start-play-video').click(function(){
            if(!videoURL){
                hybrid.makeToast("请先录制视频!");
                return false;
            }
            hybrid.plugin.video.playVideo('http://test.statics.maosui.com/Res/ResReadOlnyServer.ashx?key=' + videoURL);
        });
    });
});


